// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: 'cloud1-6gsv4k6hcacb77b6' })
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  console.log('收到请求:', JSON.stringify(event, null, 2));
  
  const { action, data, _id, query } = event
  
  try {
    console.log(`开始处理 ${action} 操作`);
    switch(action) {
      case 'add':
        return await handleAdd(data)
      case 'save':  // 新增save操作
        return await handleSave(data)
      case 'update':
        return await handleUpdate(_id, data)
      case 'delete':
        return await handleDelete(_id)
      case 'query':
        return await handleQuery(query)
      case 'recommend':
        return await handleRecommend(query)
      case 'getClothes':
        return await handleGetClothes(query)
      default:
        console.warn('无效的操作类型:', action);
        return {
          code: 400,
          message: '无效操作类型',
          suggestActions: ['add', 'update', 'delete', 'query', 'recommend']
        }
    }
  } catch (err) {
    console.error('操作失败:', err.stack || err);
    return {
      code: 500,
      message: '操作失败',
      error: err.message
    }
  }
}

// 新增推荐处理函数
async function handleRecommend(query) {
  const { userid, weather, temp, style, colorScheme } = query
  
  try {
    // 1. 确定季节
    const season = getSeasonByWeather(weather, temp)
    console.log('推荐参数:', {userid, weather, temp, style, season, colorScheme});
    
    // 2. 构建查询条件
    let queryCondition = { 
      userid,
      styles: db.RegExp({
        regexp: `^${style}$`,
        options: 'i'
      }),
      seasons: season // 添加季节条件
    }
    
    // 3. 执行查询
    const res = await db.collection('clothes')
      .where(queryCondition)
      .get()
    
    console.log('推荐查询结果:', {count: res.data.length});
    
    // 4. 处理结果 - 如果没有数据直接返回
    if (res.data.length === 0) {
      return {
        code: 200,
        message: `暂无${style}风格的${season}衣物`,
        data: [],
        season,
        style
      }
    }
    
    // 5. 如果有色系参数，按色系规则过滤
    if (colorScheme) {
      const colorRules = {
        '黑色': { top: '黑色', bottom: ['蓝色', '白色'] },
        '白色': { top: '白色', bottom: ['黑色', '棕色'] },
        '红色': { top: '红色', bottom: ['灰色', '黑色'] },
        '蓝色': { top: '蓝色', bottom: ['白色', '黑色'] },
        '黄色': { top: '黄色', bottom: ['白色', '黑色'] },
        '绿色': { top: '绿色', bottom: ['白色', '黑色'] },
        '紫色': { top: '紫色', bottom: ['白色', '黑色'] },
        '灰色': { top: '灰色', bottom: ['蓝色', '黑色'] }
      };
      
      const rule = colorRules[colorScheme];
      if (rule) {
        // 按色系规则过滤
        res.data = res.data.filter(item => {
          if (item.categories === '外套' || item.categories === '内搭') {
            return item.colors === rule.top;
          } else if (item.categories === '下装') {
            return rule.bottom.includes(item.colors);
          }
          return true; // 其他分类不限制
        });
      }
    }
    
    const clothesByCategory = groupByCategory(res.data)
    return {
      code: 200,
      data: clothesByCategory,
      season,
      style
    }
  } catch (err) {
    console.error('推荐失败:', err);
    return {
      code: 500,
      message: '推荐失败',
      error: err.message
    }
  }
}

// 根据天气和温度确定季节
function getSeasonByWeather(weather, temp) {
  const temperature = Number(temp)
  if (temperature >= 28) return '夏季'
  if (temperature <= 10) return '冬季'
  if (temperature > 10 && temperature < 20) return '春季'
  return '秋季'
}

// 按分类分组衣物
function groupByCategory(items) {
  const categories = ['外套', '内搭', '下装', '一体衣', '鞋子', '装饰', '袜子', '帽子']
  const result = {}
  
  categories.forEach(category => {
    result[category] = items.filter(item => item.categories === category)
  })
  
  return result
}

// 更新数据
async function handleUpdate(_id, data) {
  console.log('更新操作 - 文档ID:', _id, '更新数据:', JSON.stringify(data, null, 2));
  
  if (!_id) {
    console.error('缺少文档ID');
    return {
      code: 400,
      message: '缺少文档ID'
    }
  }

  try {
    console.log('正在检查文档是否存在...');
    const doc = await db.collection('clothes').doc(_id).get()
    if (!doc.data) {
      console.error('文档不存在，ID:', _id);
      return {
        code: 404,
        message: '文档不存在'
      }
    }

    // 创建更新数据副本并移除_id字段
    const updateData = {...data};
    delete updateData._id;
    console.log('处理后的更新数据:', JSON.stringify(updateData, null, 2));

    console.log('正在执行更新操作...');
    const result = await db.collection('clothes').doc(_id).update({ 
      data: {
        ...updateData,
        updatedAt: db.serverDate()
      }
    })

    console.log('更新结果:', JSON.stringify(result, null, 2));
    return {
      code: 200,
      message: '更新成功',
      data: {
        updated: result.stats.updated,
        _id: _id
      }
    }
  } catch (err) {
    console.error('更新失败:', err.stack || err);
    return {
      code: 500,
      message: '更新失败',
      error: err.message
    }
  }
}

// 新增数据
async function handleAdd(data) {
  if (!data || typeof data !== 'object') {
    return {
      code: 400,
      message: '数据格式错误，请传入完整对象'
    }
  }

  const result = await db.collection('clothes').add({ data })
  return {
    code: 200,
    message: '新增成功',
    data: result
  }
}

// 删除数据
async function handleDelete(_id) {
  if (!_id) {
    return {
      code: 400,
      message: '缺少文档ID'
    }
  }

  const result = await db.collection('clothes').doc(_id).remove()
  return {
    code: 200,
    message: '删除成功',
    data: result
  }
}

// 查询数据
async function handleQuery(query = {}) {
  // 检查必须参数
  if (!query.userid) {
    console.error('缺少用户ID参数');
    return {
      code: 400,
      message: '缺少用户ID参数'
    }
  }

  console.log('查询条件:', JSON.stringify({
    userid: query.userid,
    style: query.style || '无',
    season: query.season || '无',
    orderBy: query.orderBy || 'time',
    order: query.order || 'desc',
    skip: query.skip || 0,
    limit: query.limit || 100
  }, null, 2));

  // 构建查询条件
  const queryCondition = {
    userid: query.userid
  };

  // 添加风格筛选条件
  if (query.style) {
    queryCondition.styles = db.RegExp({
      regexp: `^${query.style}$`,
      options: 'i'
    });
  }

  // 添加季节筛选条件
  if (query.season) {
    queryCondition.seasons = query.season;
  }

  // 执行查询
  const result = await db.collection('clothes')
    .where(queryCondition)
    .orderBy(query.orderBy || 'time', query.order || 'desc')
    .skip(query.skip || 0)
    .limit(query.limit || 100)
    .get()

  // 记录查询结果
  console.log('查询结果:', JSON.stringify({
    count: result.data.length,
    data: result.data.length > 0 ? '[...]' : '[]'
  }, null, 2));
  
  if (result.data.length > 0) {
    console.log('详细数据:', JSON.stringify(result.data, null, 2));
  }

  // 处理空结果
  if (result.data.length === 0) {
    let message = '暂无衣物数据';
    if (query.style) message = `暂无${query.style}风格的衣物数据`;
    return {
      code: 200,
      message,
      data: []
    }
  }

  return {
    code: 200,
    message: '查询成功',
    data: result.data
  }
}

// 新增保存处理函数
async function handleSave(data) {
  try {
    // 检查必须字段
    if (!data.userid || !data.images) {
      return {
        code: 400,
        message: '缺少必要字段: userid或images'
      }
    }

    // 保存整套搭配到数据库
    const result = await db.collection('cloth').add({
      data: {
        userid: data.userid,
        images: data.images, // 保存所有图片链接数组
        time: data.time || new Date().toISOString().split('T')[0],
        createdAt: db.serverDate(),
        updatedAt: db.serverDate()
      }
    });

    
    return {
      code: 200,
      message: '搭配保存成功',
      data: {
        _id: result._id,
        images: data.images,
        time: data.time
      }
    }
  } catch (err) {
    console.error('保存失败:', err);
    return {
      code: 500,
      message: '保存失败',
      error: err.message
    }
  }
}
// 添加获取衣物数据的函数
async function handleGetClothes(query) {
  try {
    const { userid, page = 1, pageSize = 10 } = query;
    
    if (!userid) {
      return {
        code: 400,
        message: '缺少用户ID'
      }
    }

    const result = await db.collection('cloth')
      .where({ userid })
      .orderBy('createdAt', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get();

    return {
      code: 200,
      message: '获取成功',
      data: result.data
    }
  } catch (err) {
    console.error('获取衣物失败:', err);
    return {
      code: 500,
      message: '获取衣物失败',
      error: err.message
    }
  }
}